from PySide2.QtWidgets import QLabel
from PySide2.QtCore import Qt
from PySide2.QtGui import QPixmap, QPainter,QColor
class BatteryWidget(QLabel):
    def __init__(self, parent=None):
        super(BatteryWidget, self).__init__(parent)
        self.setPixmap(self.generate_battery_icon(0,0,0))
        self.battery_level = 100
        self.SetBattery(0,"0.0")
    def generate_battery_icon(self, level,amp,temperature=0.0):
        pixmap = QPixmap(250, 20)
        pixmap.fill(Qt.transparent)
        painter = QPainter(pixmap)
        painter.setRenderHint(QPainter.Antialiasing)
        # 绘制电池外框
        painter.drawRect(0, 0, 95, 20)
        # 绘制电池正极
        painter.fillRect(95, 5, 5, 10,QColor.fromRgb(0,0,0))

        # 计算电量栏长度
        battery_width = (level / 100) * 90
        # 绘制电量栏
        painter.fillRect(1, 3, battery_width, 15,QColor.fromRgb(255-level,int(level*2.55),0))
        painter.drawText(130,17,"{:.2f}A ".format(float(amp)))
        painter.drawText(200, 17, "{:.2f}° ".format(float(temperature)))
        painter.end()
        return pixmap

    def SetBattery(self, level,amp,temprature=0):
        if level<0:level=0
        if level>100:level=100
        self.battery_level = level
        self.setPixmap(self.generate_battery_icon(level,amp,int(temprature)))
